<?php
/*customer importer*/
class CustomerImport extends ImportBase 
{
	private $customer_table = "customers";
	private $address_table = "address_book";
	

	private $current_customer_data;
	
	
	
	public function __construct()
	{
		global $config;
		//echo "{$config['db_host']},{$config['db_user']},{$config['db_pass']},{$config['db_name']}";
		$this->set_s_db( $config['db_host'],$config['db_user'],$config['db_pass'],$config['db_name'] );
		$this->api =  Mage::getModel( "customer/customer_api" );
		$this->db = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
		$this->import_num = 100;
		
		
		parent::__construct();
	}
	
	function run()
	{
		global $config;
		
		$customers_result = $this->get_all_customer();
		$counter = 0;
		if( $customers_result->num_rows() ){
			
			while( $_customer = $customers_result->fetch_array() ){
				try {
					$customer_exist = $this->read_log( array( 'org_customer_id' => $_customer['customers_id'] ) );
					if( !$customer_exist && !$exist_customer_id = $this->check_email_duplicate( $_customer['customers_email_address'],$config['website_id'] ) ){
						$this->current_customer_data = $_customer;
						
						$newCustomer = array(
						    'firstname'  => $_customer['customers_firstname'],
						    'lastname'   => $_customer['customers_lastname'],
						    'email'      => $_customer['customers_email_address'],
						    'password_hash'   => $_customer['customers_password'],					    
						    'store_id'   => $config['default_store'],
						    'website_id' => $config['website_id'],
						    'created_at' => $_customer['customers_info_date_account_created']
						);
						//print_r( $newCustomer );
						//echo '<br />';
						$new_customer_id = $this->api->create( $newCustomer );
						$this->log( array( 'org_customer_id' => $_customer['customers_id'],'customer_id' => $new_customer_id ) );
						$this->import_address( $new_customer_id,$_customer['customers_id'] );
						$this->import_suscribe( $_customer['customers_email_address'],$_customer['customers_newsletter'] );
						$this->transation_commit();
						
						
					}else{
						$this->log( array( 'org_customer_id' => $_customer['customers_id'],'customer_id' => $exist_customer_id ) );
					}
				} catch ( Exception $e ) {
					echo __LINE__;
					echo $e->getMessage ();
					exit ( 1 );
				}
				
			}
		}	
		
	}
	
	function check_email_duplicate( $email,$website_id )
	{
		$select = $this->db->select()
            ->from('customer_entity', array('email'))
            ->where('email=?', $email)
            ->where('website_id=?', (int) $website_id);
        if( $this->db->fetchOne($select) ){
        	return true;
        }else return false;
            
	}
	
	function get_all_customer()
	{
		global $config;
		$db = new myMysqlDB( $config['db_host'],$config['db_user'],$config['db_pass'],$config['db_name'] );
		$query = "select c.*,ci.customers_info_date_account_created from `{$this->customer_table}` c left join customers_info ci on c.customers_id =ci.customers_info_id left join `{$this->log_table}` log ON c.customers_id = log.org_customer_id WHERE log.org_customer_id IS NULL limit 500";
		
		$db->query( $query );
		return $db;
	}
	
	function import_suscribe( $customer_email,$suscribe )
	{
		try {
			if( $customer_email && $suscribe ){
				$data = array();
		       
		        $data['subscriber_email']  = $customer_email;
		       		
		        $validators = array('subscriber_email' => 'EmailAddress');
		        $filters = array();
		        $input = new Zend_Filter_Input($filters, $validators, $data);
		       
		        if (!( $input->hasInvalid() || $input->hasMissing() ) ) {
					Mage::getModel('newsletter/subscriber')->subscribe($customer_email);
        		}
			}
			return '';
		} catch ( Exception $e ) {
			echo __LINE__;
			echo $e->getMessage ();
			exit ( 1 );
		}
	}
	function import_address( $customer_id,$os_customer_id )
	{	
		try {
			$addresses = $this->get_addresses( $os_customer_id );	
			//echo '<br />';
			//print_r( $addresses );
			$address_model = Mage::getModel('customer/address');
			$customer_model = Mage::getModel('customer/customer');
			$customer_model->load( $customer_id );
			
			if( count( $addresses ) ){
				foreach( $addresses as $_address ){
					$address_model->unsetData();
			        $address_model->setData($_address);
			        $address_model->setCustomerId($customer_id);
			        $address_model->setId(null);
			        $address_model->save();
			       
			        if( $_address['id'] == $this->current_customer_data['customers_default_address_id'] ){
			        	$addressId = $address_model->getId();
			        	
	                    $customer_model->setDefaultBilling($addressId);
	                    $customer_model->setDefaultShipping($addressId);
	                    $customer_model->save();
			        }
				}
			}
			unset( $address_model );
			unset( $customer_model );
		
		} catch ( Exception $e ) {
			echo __LINE__;
			echo $e->getMessage ();
			exit ( 1 );
		}
		

	}
	
	function get_addresses( $os_customer_id )
	{
		$select = "SELECT `address_book_id` `id`, `customers_id`, `entry_firstname` `firstname`";
		$select .= ", `entry_lastname` `lastname`, `entry_street_address` `street1`";
		$select .= ", `entry_company` `company` ";
		$select .= ", `entry_postcode` `postcode`, `entry_city` `city`";
		$select .= ", `entry_state` `region`, `entry_country_id` `country_id`";
		$select .= ", `entry_zone_id` `region_id` FROM `{$this->address_table}` WHERE customers_id='{$os_customer_id}'";
		$this->s_db->query( $select );
		$addresses = $this->s_db->af();
		
		$customer_addresses = array();
		if( !empty( $addresses ) ){
			
			foreach( $addresses as $_address ){
				$contry_id_org = $_address['country_id'];
				
				foreach( $_address as $address_field => $value ){
					if ($address_field == 'street1') {
	                    $address_field = 'street';
	                    $_address[ $address_field ] = $value;
	                }
	                if ($address_field == 'country_id') {
	                    $value = $this->getCountryCodeById($value);
	                    
	                    $_address[$address_field] = $value;	                    
	                    
	                    $_address[ 'country' ] = $value;
	                }
	                if ($value>0 && $address_field == 'region_id' ) {
	                	$return_value = '';
	                    $value = $this->analysis_zone_id( $this->getCountryCodeById( $contry_id_org ),$value,$return_value );
	                    if( $value ){
	                    	unset( $_address['region'] );
	                    	$_address[ $address_field ] = $value;
	                    }else{
	                    	unset( $_address['region_id'] );
	                    	if( $return_value ){
	                    		$_address['region'] = $return_value;
	                    	}
	                    }
	                    
	                    
	                }else if( $value == 0 && $address_field == 'region_id' ){
	                	unset( $_address['region_id'] );
	                }
	                
	                if ( $address_field == 'region' && (int) $value ) {	    
	                	unset( $_address['region'] );
	                }
	               
	                if (in_array($address_field, array('customers_id'))) {
						unset($_address[$address_field]);
	                }
	                
	                
				}
				$_address['telephone'] = $this->getCustomerTEL( $os_customer_id );
				$customer_addresses[] = $_address;
			}
		}
		
		return $customer_addresses;
	}
	
	
	function getCountryCodeById( $id )
	{
		static $country_code;
		if( isset( $country_code[ $id ] ) ){
			return $country_code[ $id ];
		}else{
			$query = "select * from countries where countries_id='{$id}'";
			$this->s_db->query( $query );
			if( $this->s_db->num_rows() ){
				$this->s_db->next_record();
				$country_code[ $id ] = $this->s_db->f( "countries_iso_code_2" ) == 'FX' ? 'FR':$this->s_db->f( "countries_iso_code_2" );
				return $country_code[ $id ];
			}
		}
	}
	
	function analysis_zone_id( $country_code,$zone_id,&$return_value )
	{
		static $zones_data;
		static $magento_region;
		$key = $country_code.'_'.$zone_id;
		
		if( $zone_id > 0 ){
			if( empty( $zones_data ) ){
				$query = "select * from zones";
				
				$this->s_db->query( $query );
				$zones_array = $this->s_db->af();
				foreach( $zones_array as $zone ){
					$zone_name = $country_code == 'FR' ? str_replace( ' ','-',$zone['zone_name'] ):$zone['zone_name'];
					$zones_data[ $zone['zone_id'] ] = $zone_name;
				}
			}
			
			if( isset( $zones_data[ $zone_id ] ) ){
				$return_value = $zones_data[ $zone_id ];
				$zone_model = Mage::getModel( "directory/region" );		
				Mage::app()->getLocale()->setLocaleCode('en_US');
				$zone_model->loadByName( $zones_data[ $zone_id ],$country_code );
				
				$magento_region[ $key ] = $zone_model->getId();		
				return $magento_region[ $key ];				
			}else return false;
		}else return false;
	}
	
	function getCustomerTEL( $os_customer_id )
	{
		$select = "SELECT customers_telephone FROM `{$this->customer_table}` WHERE customers_id='{$os_customer_id}'";
		$this->s_db->query( $select );
		if( $this->s_db->num_rows() ){
			$this->s_db->next_record();
			return $this->s_db->f('customers_telephone');
		}else return '';
	}
}